package top.kiterunner.learning.concurrency_test.ReentrantLockDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/7.
 */
public class ReentrantLockDemo2 {

    // 使用synchronized锁定的话，如果遇到异常，jvm会自动释放锁
    // 但是对于ReentrantLock，需要手动释放锁，因此，常常在finally中进行锁的释放
    Lock lock = new ReentrantLock();

    public void method1() {
        try {
            lock.lock();

            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);

                System.out.println(Thread.currentThread().getName() + " sleep " + i + "th second.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " execute method2.");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo2 rld2 = new ReentrantLockDemo2();

        new Thread(rld2::method1, "Thread_1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(rld2::method2, "Thread_2").start();
    }
}
